import fs from 'fs'
import path = require('path')
import * as cheerio from 'cheerio'
import { Compiler } from 'webpack'
import generateResourceMonitor from './resourceMonitor'
import { validateResource } from './utils'

export function originalHandle(compiler: Compiler) {
  const html = fs.readFileSync(path.resolve(compiler.outputPath, './index.html'), 'utf8')
  const scriptResourceSetUrlSegment: Array<string> = []
  const linkResourceUrlSegment: Array<string> = []
  const $ = cheerio.load(html)

  $('script').each((index, element) => {
    const src = $(element).attr('src')
    if (src) {
      if (validateResource(src)) {
        scriptResourceSetUrlSegment.push(`['${src}', false]`)
      }
      $(element)
        .attr('onerror', '__onResourceLoadError__(this, { delay: 1000 })')
        .attr('onload', '__onResourceLoad__(this)')
    }
  })

  $('link').each((index, element) => {
    const href = $(element).attr('href')
    if (href) {
      if (validateResource(href)) {
        linkResourceUrlSegment.push(`['${href}', false]`)
      }
      $(element)
        .attr('onerror', '__onResourceLoadError__(this, { delay: 1000 })')
        .attr('onload', '__onResourceLoad__(this)')
    }
  })

  const resourceMonitor = generateResourceMonitor({
    links: linkResourceUrlSegment.join(', '),
    scripts: scriptResourceSetUrlSegment.join(', ')
  })

  $('head').prepend(`<script>${resourceMonitor}</script>`)

  fs.writeFileSync(path.resolve(compiler.outputPath, './index.html'), $.html(), 'utf8')
}